<template>
  <div class="padding-container preview-wrap" v-if="!showVisual">
    <a class="tip-part" href="/control/user">{{ $root.lang.control.visual.list.tip }}</a>
  </div>
	<div class="padding-container preview-wrap" v-else-if="showVisual">
		<div class="title-part">
      <el-button size="mini" type="primary" class="pull-right" @click="toCreate()" v-show="showBtn">{{ $root.lang.control.visual.list.add }}</el-button>
		</div>
		<el-form ref="tableParams" :inline="true" :model="tableParams" size="small">
      <el-form-item :label="$root.lang.control.visual.list.webName">
        <el-input v-model="tableParams.webName"></el-input>
      </el-form-item>
      <el-form-item :label="$root.lang.control.visual.list.deviceType">
        <el-select v-model="tableParams.deviceType" :placeholder="$root.lang.control.visual.list.select" clearable>
          <el-option :label="item.deviceType" :value="item.id" :key="item.id" v-for="item in deviceTypeList"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$root.lang.control.visual.list.temporarySave">
        <el-select v-model="tableParams.temporarySave" :placeholder="$root.lang.control.visual.list.select">
          <el-option :label="item.title" :value="item.value" :key="item.value" v-for="item in baseState.temporarySave"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$root.lang.control.visual.list.delFlg">
        <el-select v-model="tableParams.delFlg" :placeholder="$root.lang.control.visual.list.select">
          <el-option :label="item.title" :value="item.value" :key="item.value" v-for="item in baseState.delFlag"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="searchAction()" >{{ $root.lang.control.visual.list.query }}</el-button>
        <el-button size="small" @click="searchAction(true)" >{{ $root.lang.control.visual.list.empty }}</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="listLoading"
      :data="pageList"
      :empty-text="$root.lang.control.visual.list.noData"
      size="small"
      border
      style="width: 100%"
      :header-cell-style="{'text-align':'center'}"
      >
      <el-table-column
        align="center"
        :label="$root.lang.control.visual.list.webName">
        <template slot-scope="scope">
          <span>{{ scope.row.webName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$root.lang.control.visual.list.deviceType">
        <template slot-scope="scope">
          <p v-if="deviceTypeList.length != 0">{{ deviceTypeList.find(item => item.id === scope.row.deviceType) == null ? 
            scope.row.deviceType : deviceTypeList.find(item => item.id === scope.row.deviceType).deviceType }}</p>
          <p v-else>{{ scope.row.deviceType }}</p>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$root.lang.control.visual.list.temporarySave">
        <template slot-scope="scope">
          <p>{{ baseState.temporarySave, scope.row.temporarySave, '未发布' | matchValue }}</p>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$root.lang.control.visual.list.delFlg">
        <template slot-scope="scope">
          <p>{{ baseState.delFlag, scope.row.delFlg, '未删除' | matchValue }}</p>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$root.lang.control.visual.list.webDesc">
        <template slot-scope="scope">
          <span>{{ scope.row.webDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$root.lang.control.visual.list.creDate">
        <template slot-scope="scope">
          <span>{{ scope.row.creDate | dateFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :width="alignWidth"
        align="center"
        label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="toPreview(scope.$index, scope.row)">{{ $root.lang.control.visual.list.preview }}</el-button>
          <el-button
            size="mini"
            type="primary"
            v-if="scope.row.temporarySave == 1"
            @click="toDownload(scope.$index, scope.row)">{{ $root.lang.control.visual.list.download }}</el-button>
          <el-button
            size="mini"
            type="primary"
            v-if="scope.row.temporarySave == 0 && scope.row.delFlg == 0"
            @click="toUpdate(scope.$index, scope.row)">{{ $root.lang.control.visual.list.update }}</el-button>
          <el-button
            size="mini"
            type="primary"
            v-if="scope.row.temporarySave == 0 && scope.row.delFlg == 0"
            @click="toRelease(scope.$index, scope.row)">{{ $root.lang.control.visual.list.release }}</el-button>
          <el-button
            size="mini"
            type="danger"
            v-if="scope.row.temporarySave == 0 && scope.row.delFlg == 0"
            @click="toDelete(scope.$index, scope.row)">{{ $root.lang.control.visual.list.delete }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="tableTotal>0"
      @size-change="sizeChange"
      @current-change="pageChange"
      @prev-click="pageChange"
      @next-click="pageChange"
      :current-page="tableParams.pageNum"
      :page-sizes="[10, 30, 50, 100]"
      :page-size="tableParams.pageSize"
      layout="total, sizes, prev, pager, next"
      :total="tableTotal">
    </el-pagination>
	</div>
</template>

<script>
import '@/options/baseState'
export default {
	name: 'PageList',
	data() {
		return {
			tableParams: {
				pageNum: 1,
				pageSize: 10,
        webName: null,
        deviceType: null,
        delFlg: 0,
        temporarySave: 1
			},
			listLoading: false,
      pageList: [],
      tableTotal: 0,
      deviceTypeList: [],
      showBtn: true,
      showVisual: false,
      baseState: baseState,
      alignWidth: 200
		}
	},
  methods: {
    getReceive(data) {
      this[data.key] = data.value
    },
    reloadTable() {
      this.searchAction(true);
    },
    toCreate() {
      window.open(this.Options.links.visual + '?A=' + this.store.getters.status)
    },
    toPreview(index, row) {
      window.open(this.Options.links.visual + 'preview' + '?A=' + this.store.getters.status + '&I=' + row.id)
    },
    toDownload(index, row) {
      this.$confirm(this.$root.lang.confirm.downloadFile, this.$root.lang.confirm.tips, {
        confirmButtonText: this.$root.lang.confirm.downloadImmediately,
        cancelButtonText: this.$root.lang.confirm.noDownload,
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: this.$root.lang.confirm.process,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        let param = {}
        this.request({
          url: '/web/preview/' + row.id,
          method: 'get',
        }).then(response => {
          let result = response.result
          let componentData = JSON.parse(result.substring(1, result.length - 1))
          let datas = []
          componentData.forEach(component => {
            let item = {}
            item.id = component.id
            item.component = component.component
            item.label = component.label
            item.propValue = component.propValue
            if(component.component == 'v-button') {
              item.publish = component.events.publish
              item.publishTopic = component.events.publishTopic
              item.publishPayload = component.events.publishPayload
              if(item.publish) {
                datas.push(item)
              }
            } else if(component.component == 'v-text' || component.component == 'v-text' || component.component == 'v-line'
             || component.component == 'v-bar' || component.component == 'v-pie') {
              item.subscribe = component.events.subscribe
              item.subscribeTopic = component.events.subscribeTopic
              if(item.subscribe) {
                datas.push(item)
              }
            }
          })
          param.webId = row.webId
          param.data = datas
          loading.close()
          this.toGenerateFile(param)
        }).catch(error => {
          loading.close()
          this.$message({
            message: error.errmsg == undefined ? this.$root.lang.control.visual.list.errorTip : error.errmsg,
            type: 'error',
            duration: 3 * 1000
          })
        })
      }).catch(() => {
      })    
    },
    toGenerateFile(param) {
      this.request({
        url: '/web/generate-profile',
        method: 'post',
        data: param,
        responseType: "blob"
      }).then(response => {
        // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
        let blob = new Blob([response.data], {type: response.data.type});
        // 创建一个a标签
        const link = document.createElement('a')
        // 设置a标签的下载属性
        link.download = 'joshvm.json';
        // 将a标签设置为隐藏
        link.style.display = 'none';
        // 把之前处理好的地址赋给a标签的href
        link.href = URL.createObjectURL(blob);
        // 将a标签添加到body中
        document.body.appendChild(link);
        // 执行a标签的点击方法
        link.click();
        // 下载完成释放URL对象
        URL.revokeObjectURL(link.href)
        // 移除a标签
        document.body.removeChild(link)

      }).catch(error => {
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
    },
    sizeChange(val) {
      this.tableParams.pageNum = 1
      this.tableParams.pageSize = val
      this.fetchData()
    },
    pageChange(val) {
      this.tableParams.pageNum = val
      this.fetchData()
    },
    toUpdate(index, row) {
      window.open(this.Options.links.visual + '?A=' + this.store.getters.status + '&I=' + row.id
       + '&N=' + row.webName + '&T=' + row.deviceType + '&D=' + row.webDesc)
    },
    searchAction(reset) {
      if(reset) {
        this.tableParams = {
          pageNum: 1,
          pageSize: 10,
          webName: null,
          deviceType: null,
          delFlg: 0,
          temporarySave: 1
        }
      } else {
        this.tableParams.pageNum = 1
      }
      if(this.tableParams.temporarySave == 1) {
        this.alignWidth = 200
      } else {
        this.alignWidth = 300
      }
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      this.request({
        url: '/web/page',
        method: 'post',
        data: this.$root.optionProcess(this.tableParams)
      }).then(response => {
        this.pageList = response.rows
        this.tableTotal = response.total
        this.listLoading = false
      }).catch(error => {
        this.pageList = []
        this.listLoading = false
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
    },
    getDeviceType() {
      this.request({
        url: '/web/type/page',
        method: 'post',
        data: {}
      }).then(response => {
        this.deviceTypeList = response.rows
      }).catch(error => {
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
    },
    toDelete(index, row) {
      this.$confirm(this.$root.lang.confirm.deleteVisual, this.$root.lang.confirm.tips, {
        confirmButtonText: this.$root.lang.confirm.deleteImmediately,
        cancelButtonText: this.$root.lang.confirm.noDeletion,
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: this.$root.lang.confirm.process,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.request({
          url: '/web/del/' + row.id,
          method: 'get',
        }).then(response => {
          loading.close()
          this.$message({
            message: this.$root.lang.confirm.operateSuccess + this.$root.lang.confirm.visualDelete,
            type: 'success',
            duration: 3 * 1000
          })
          this.searchAction()
        }).catch(error => {
          loading.close()
          this.$message({
            message: error.errmsg,
            type: 'error',
            duration: 3 * 1000
          })
        })
      }).catch(() => {
        
      })
    },
    toRelease(index, row) {
      this.$confirm(this.$root.lang.confirm.releaseVisual, this.$root.lang.confirm.tips, {
        confirmButtonText: this.$root.lang.confirm.releaseImmediately,
        cancelButtonText: this.$root.lang.confirm.noRelease,
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: this.$root.lang.confirm.process,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.request({
          url: '/web/release/' + row.id,
          method: 'get',
        }).then(response => {
          loading.close()
          this.$message({
            message: this.$root.lang.confirm.operateSuccess + this.$root.lang.confirm.visualRelease,
            type: 'success',
            duration: 3 * 1000
          })
          this.searchAction()
        }).catch(error => {
          loading.close()
          this.$message({
            message: error.errmsg,
            type: 'error',
            duration: 3 * 1000
          })
        })
      }).catch(() => {
        
      })
    },
  },
  created() {
    if(this.Cookies.get('T') == '2') {
      if(this.Cookies.get('O') == '1') {
        this.showBtn = false
      }
		} 
    this.showVisual = this.Cookies.get('V') == 3 ? true : false
    if(this.showVisual) {
      this.getDeviceType()
      this.fetchData()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
	.padding-container {
		text-align:left;
		.title-part {
			text-align: left;
			font-size: 18px;
			padding-bottom: 40px;
		}
    .tip-part {
			text-align: left;
			font-size: 15px;
			padding-bottom: 40px;
      color: red;
		}
	}
</style>